<?php
// +----------------------------------------------------------------------
// |MCPHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------
namespace addons\WeChat\controller;

require_once __DIR__ . '/../sdk/include.php';

/**
 * Class AppPay 微信开放平台支付联调
 * @package plugins\WeChat\controller
 * @Author jokerfei [ jokerfei377@gmail.com ]
 * @created 2019/9/9 22:07
 */
class MiniPayV3 extends Base
{

    public $mini_config;

    /**
     * 返回实例本身
     * MiniPay constructor.
     * @param null $config
     */
    public function __construct($config = null)
    {
        parent::__construct();
        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }

        $this->mini_config = [
            'appid'        => $this->config['mini_appid'],
            'appsecret'    => $this->config['mini_appsecret'],
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id'       => $this->config['mchid'],
            'mch_key'      => $this->config['key'],
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key'      => $this->config['sslkey_path'],
            'ssl_cer'      => $this->config['sslcert_path'],
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path'   => '',

            //V3部分
            'mch_v3_key'   => $this->config['key_v3'],
            'cert_public'  => $this->config['cert_public_v3'],
            'cert_private' => $this->config['cert_private_v3'],
        ];
    }

    /**
     * 创建支付一个订单
     * @param $data
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @created 2020/2/19 16:41
     */
    public function pay($data)
    {
        $body         = $data['body'];
//        $time_expire  = $data['time_expire'] - 60; //订单取消前取消支付状态
        $total_fee    = $data['total_fee'];
        $out_trade_no = $data['out_trade_no'];
        //组装订单数据
        $body = preg_replace('/\r\n/', '', $body);
        $body = mb_strlen($body) > 40 ? mb_substr($body, 0, 40, 'utf-8') . '...' : $body;
        
        // 组装参数，可以参考官方商户文档
        $options = [
            'appid' => $this->mini_config['appid'],
            'mchid' => $this->mini_config['mch_id'],
            'description'  => $body,
            'out_trade_no' => $out_trade_no,
            'notify_url'   => sysconfig('site', 'site_domain') . '/notify/wechat/miniV3',
            'amount'       => [
                'total'    => $total_fee * 100,
                'currency' => 'CNY',
            ],
            'payer'        => [
                'openid' => $data['xcx_openid'],
            ],
//            'time_expire'  => date(DATE_ATOM, time() + 3600),
        ];
        // return $this->mini_config;
        // 创建接口实例
        $wechat = new \WePayV3\Order($this->mini_config);
        // 创建订单
        return $wechat->create('jsapi', $options);
    }

    /**
     * 查询订单
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @created 2020/2/19 16:43
     */
    public function queryOrder($transaction_id, $out_trade_no)
    {
        try {
            // 创建接口实例
            $wechat = new \WePayV3\Order($this->mini_config);
            $result = $wechat->query($out_trade_no);
            // 订单数据处理
            return $result;
        } catch (\Exception $e) {
            \think\facade\Log::info('查询订单出错' . $e->getMessage());
        }
    }

    /**
     * 退款
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @created 2020/2/19 16:41
     */
    public function backPay($data)
    {
        $total_fee     = floatval($data['total_fee']);
        $refund_fee    = floatval($data['refund_fee']);
        $refund_reason = $data['refund_reason'];
        $transaction_id  = $data['transaction_id'];
        $out_refund_no = $data['out_refund_no'];
        //组装订单数据
        $refund_reason    = preg_replace('/\r\n/', '', $refund_reason);
        $refund_reason    = mb_strlen($refund_reason) > 40 ? mb_substr($refund_reason, 0, 40, 'utf-8') . '...' : $refund_reason;
        $wechat  = new \WePayV3\Order($this->mini_config);
        $options = [
            'out_refund_no' => $out_refund_no,
            'transaction_id'  => $transaction_id, //订单号
            'amount'        => [
                'refund'   => $refund_fee * 100, //退款金额
                'total'    => $total_fee * 100, //订单总金额
                'currency' => 'CNY',
            ],
            'reason'        => $data['refund_reason'], //退款理由
            'notify_url'    => sysconfig('site', 'site_domain') . '/notify/wechat/miniV3Back',
        ];
        // 创建退款订单
        $result = $wechat->createRefund($options);
        \think\facade\Log::info($result);
        if ($result['status'] == 'SUCCESS') {
            return $result;
        } else {
            return false;
        }
    }

    //退款状态查询
    public function bcakQueryPay($out_refund_no)
    {

    }

    //同步回调
    public function verifyReturn($out_trade_no)
    {

    }

    //异步回调
    public function initWechatPay()
    {
        // 创建接口实例
        $wechat = new \WePayV3\Order($this->mini_config);
        // 订单数据处理
        return $wechat;
    }
}
